﻿using System.Collections.Generic;
using System.Linq;

using DotNetLib.Windows.Forms;

using ExtensibleEventViewer.Core.Interfaces;
using ExtensibleEventViewer.Core.Primitives;


namespace ExtensibleEventViewer.Console.DomainModel
{
	public class SubItemsFilter : IFilter
	{
		private static readonly SubItemsFilter _instance = new SubItemsFilter();

		public static SubItemsFilter Instance
		{
			get
			{
				return _instance;
			}
		}

		public bool Belongs(object obj)
		{
			if (AppSettings.Instance.EnabledEventLogFilters.Length == 0)
			{
				return true;
			}

			int count = (from enabled in AppSettings.Instance.EnabledEventLogFilters
			             where enabled.Value
			             select enabled.Value).Count();

			if (count == 0)
			{
				return true;
			}
	
			if (obj is EventLogRecord)
			{
				EventLogRecord adapter = (EventLogRecord)obj;

				foreach (KeyValuePair<string, bool> enabledEventLogFilter in AppSettings.Instance.EnabledEventLogFilters)
				{
					if (enabledEventLogFilter.Value)
					{
						foreach (IEventLogFilter filter in AppSettings.Instance.EventLogFilters)
						{
							if (filter.FilterID.Equals(enabledEventLogFilter.Key))
							{
								if (filter.IsMatch(adapter))
								{
									return true;
								}
							}
						}
					}
				}
			}
			else
			{
				return true;
			}

			return false;
		}
	}
}
